<template>

  <div class="divSize">
    <h1 style="font-size: 26px; text-align: center">资料填写</h1>
    <br />
    <el-form
      ref="ruleFormRef"
      :model="studentInfo"
      status-icon
      :rules="rules"
      label-width="80px"
      label-position="right"
      :inline="true"
    >
      <h1>一、个人档案</h1>
      <br />
      <el-row style="min-width: 1200px;">
        <el-row>
          <el-col :span="4">
            <el-form-item label="姓名" prop="stuName">
              <el-input
                :disabled="disabled"
                v-model="studentInfo.stuName"
                type="text"
                style="width: 150px"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-col :span="4">
          <el-form-item label="性别" prop="stuSex" :label-width="labelWidth">
            <el-select
              :disabled="disabled"
              v-model="studentInfo.stuSex"
              placeholder="
            性别"
              style="width: 120px"
            >
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="邮箱" prop="email" :label-width="labelWidth">
            <el-input
              :disabled="disabled"
              v-model="studentInfo.email"
              type="text"
              style="width: 200px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="电话" prop="stuPhone" :label-width="labelWidth">
            <el-input
              :disabled="disabled"
              v-model="studentInfo.stuPhone"
              type="number"
              style="width: 150px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <div style="margin-left: 20px;">
            <el-upload
              :disabled="disabled"
              class="avatar-uploader"
              :headers="token"
              action="/api/student/signup/upload"
              name="stuImage"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="studentInfo.stuImage" :src="studentInfo.stuImage" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
                一寸照片
              </el-icon>
            </el-upload>
          </div>
        </el-col>
      </el-row>
      <el-row style="position: relative; margin-top: -100px">
        <el-col :span="5">
          <el-form-item label="学号" prop="studentId">
            <el-input
              :disabled="disabled"
              v-model="studentInfo.studentId"
              type="text"
              style="width: 150px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="年级" prop="stuGrade" :label-width="labelWidth">
            <el-select
              :disabled="disabled"
              v-model="studentInfo.stuGrade"
              placeholder="年级"
              style="width: 120px"
            >
              <el-option label="大一" value="大一" />
              <el-option label="大二" value="大二" />
              <el-option label="大三" value="大三" />
              <el-option label="大四" value="大四" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="学院" prop="stuDepartment" :label-width="labelWidth">
            <el-select
              :disabled="disabled"
              v-model="studentInfo.stuDepartment"
              placeholder="请选择你的学院"
              style="width: 200px"
            >
              <el-option label="计算机科学与工程学院" value="计算机科学与工程学院" />
              <el-option label="电子科学与工程学院" value="电子科学与工程学院" />
              <el-option label="国际商学院" value="国际商学院" />
              <el-option label="管理学院" value="管理学院" />
              <el-option label="艺术学院" value="艺术学院" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="专业" prop="stuSpeciality" :label-width="labelWidth">
            <el-select
              v-model="studentInfo.stuSpeciality"
              :disabled="disabled"
              placeholder="选择专业"
              style="width: 200px"
              @visible-change="visibleChange"
            >
              <el-option
                v-for="item in stuSpeciality"
                :key="item.value"
                :label="item.value"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="班级" prop="year">
            <!--        年-->
            <el-date-picker
              :disabled="disabled"
              v-model="studentInfo.year"
              type="year"
              placeholder="选择年份"
              style="width: 150px"
            />
            <span style="margin: 0 5px">级</span>
            <!--        班-->
            <el-select
              v-model="studentInfo.stuSpeciality"
              :disabled="disabled"
              placeholder="选择班级"
              style="width: 250px"
              @visible-change="visibleChange"
            >
              <el-option
                v-for="item in stuSpeciality"
                :key="item.value"
                :label="item.value"
                :value="item.value"
              />
            </el-select>
            <!--          几班-->
            <el-input-number
              :disabled="disabled"
              v-model="studentInfo.classNumber"
              :min="1"
              style="width: 150px"
            />
            <span style="margin: 0 5px">班</span>
          </el-form-item>
        </el-col>
      </el-row>

      <h1>二、竞赛获奖及考证信息</h1>
      <span style="font-size: 10px; color: #909399"
        >（注：若无获奖信息，请点击右侧减号将奖项列表删除）</span
      ><br /><br />
      <el-form-item
        v-for="(con, index) in studentInfo.contest"
        :key="con.key"
        :label="'奖项' + (index + 1)"
        :prop="'contest.' + index + '.conName'"
        :rules="{
          required: true,
          message: '奖项不能为空',
          trigger: 'blur'
        }"
      >
        <el-input
          :disabled="disabled"
          placeholder="获奖名称"
          v-model="con.conName"
          clearable
          style="width: 400px; height: 30px"
        />
        <span class="demonstration">获奖时间</span>
        <el-date-picker
          :disabled="disabled"
          v-model="con.conTime"
          type="date"
          placeholder="选择获奖日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
        <!--删除-->
        <el-button
          :disabled="disabled"
          circle
          size="small"
          style="border: 0"
          @click.prevent="removeContest(con)"
        >
          <el-icon color="#F56C6C" size="23">
            <RemoveFilled />
          </el-icon>
        </el-button>
      </el-form-item>
      <!--添加-->
      <el-form-item style="margin-left: -25px">
        <el-button :disabled="disabled" circle size="small" style="border: 0" @click="addContest">
          <el-icon color="#E6A23C" size="23">
            <CirclePlusFilled />
          </el-icon>
        </el-button>
      </el-form-item>

      <h1>三、个人技能</h1>
      <br />
      <el-form-item label="技术方向" prop="stuSkill">
        <el-select
          :disabled="disabled"
          v-model="studentInfo.stuSkill"
          placeholder="请选择你的技术方向"
          clearable
          style="width: 200px"
        >
          <el-option label="前端" value="前端" />
          <el-option label="后端" value="后端" />
          <el-option label="全栈" value="全栈" />
        </el-select>
      </el-form-item>
      <br />
      <el-form-item label="技术栈" prop="stuSkillStack">
        <el-input
          :disabled="disabled"
          v-model="studentInfo.stuSkillStack"
          maxlength="200"
          placeholder="个人技术栈（掌握的开发语言，开发框架，会使用的开发工具等个人技能）"
          show-word-limit
          type="textarea"
          resize="none"
          rows="5"
          style="width: 550px"
        />
      </el-form-item>

      <h1>四、个人意向</h1>
      <br />
      <el-form-item label="意向" prop="stuIntention">
        <el-input
          :disabled="disabled"
          v-model="studentInfo.stuIntention"
          maxlength="200"
          placeholder="个人意向（进入卓越班想要学习什么，或者个人的发展方向）"
          show-word-limit
          type="textarea"
          resize="none"
          rows="5"
          style="width: 550px"
        />
      </el-form-item>

      <br />
      <el-form-item style="margin-left: 40%; margin-top: 15px">
        <el-button type="warning" @click="cancer">{{ cancerButton }}</el-button>
        <span style="width: 100px"></span>
        <el-button :disabled="disabled" type="primary" @click="submitForm(ruleFormRef)"
          >保存
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { userStore } from '@/stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import { checkEmail, checkPhone, checkStudentId } from '@/utils/checkRule'
import { getInfo, saveInfo } from '@/apis/signup'
import { getToken } from '@/utils/token'
import Router from '@/router'

const userstore = userStore()
const ruleFormRef = ref<FormInstance>()
const disabled = ref(true)
const cancerButton = ref('修改')
const token = ref({ token: getToken() })
const stuSpeciality = ref([{ value: '' }])
const labelWidth = ref(60)
const stuSpecialityList = ref([
  {
    stuDepartment: '计算机科学与工程学院',
    stuSpeciality: [
      { value: '软件工程' },
      { value: '网络工程' },
      { value: '物联网工程' },
      { value: '数据科学与大数据技术' },
      { value: '区块链工程' },
      { value: '计算机网络技术' },
      { value: '软件技术' }
    ]
  },
  {
    stuDepartment: '电子科学与工程学院',
    stuSpeciality: [
      { value: '电子信息工程' },
      { value: '自动化' },
      { value: '通信工程' },
      { value: '人工智能' },
      { value: '电子信息工程技术' },
      { value: '电气自动化技术' }
    ]
  },
  {
    stuDepartment: '国际商学院',
    stuSpeciality: [
      { value: '电子商务' },
      { value: '金融工程' },
      { value: '国际经济与贸易' },
      { value: '互联网金融' },
      { value: '商务英语' },
      { value: '物流管理' }
    ]
  },
  {
    stuDepartment: '管理学院',
    stuSpeciality: [
      { value: '财务管理' },
      { value: '会计学' },
      { value: '工程造价' },
      { value: '工程管理' },
      { value: '旅游管理（本）' },
      { value: '旅游管理（专）' },
      { value: '大数据与财务管理' },
      { value: '大数据与会计' }
    ]
  },
  {
    stuDepartment: '艺术学院',
    stuSpeciality: [
      { value: '环境设计' },
      { value: '视觉传达设计' },
      { value: '音乐表演（本）' },
      { value: '音乐表演（专）' },
      { value: '播音与主持（本）' },
      { value: '播音与主持艺术（专）' },
      { value: '舞蹈表演（本）' },
      { value: '舞蹈表演（专）' },
      { value: '数字媒体技术' },
      { value: '艺术设计' }
    ]
  }
])

interface ContestItem {
  key: number
  conId: number
  conName: String
  conTime: String
}

const studentInfo = ref({
  stuName: '',
  stuPhone: '',
  studentId: '',
  email: '',
  stuGrade: '',
  stuSex: '',
  stuSpeciality: '',
  year: Date,
  classNumber: '',
  stuClass: '',
  stuDepartment: '',
  stuImage: '',
  stuSkill: '',
  stuSkillStack: '',
  stuIntention: '',
  contest: [
    {
      key: '',
      conId: '',
      conName: '',
      conTime: ''
    }
  ]
})

const contest = ref<ContestItem>([
  {
    key: 1,
    conId: '',
    conName: '',
    conTime: ''
  }
])
const visibleChange = (visible: boolean) => {
  for (let i = 0; i < stuSpecialityList.value.length; i++) {
    if (studentInfo.value.stuDepartment === stuSpecialityList.value[i].stuDepartment) {
      stuSpeciality.value = stuSpecialityList.value[i].stuSpeciality
    }
  }
}
const getStudentInfo = () => {
  getInfo(userstore.userInfo.studentId).then((res) => {
    console.log('获取学生信息')
    if (res.data.code === 1) {
      console.log('获取成功')
      studentInfo.value = res.data.data
      if (studentInfo.value.contest.length === 0) {
        studentInfo.value.contest = contest.value
      }
    } else {
      console.log('获取失败')
      ElMessage({ type: 'error', message: res.data.msg })
    }
  })
}
studentInfo.value.contest = contest.value
onMounted(() => {
  disabled.value = true
  getStudentInfo()
  userstore.defaultUrl = '/signup'
})
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  studentInfo.value.stuImage = response.data
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (File) => {
  if (File.type !== 'image/jpeg') {
    ElMessage.error('上传头像图片只能是 JPG 格式!')
    return false
  } else if (File.size / 1024 / 1024 > 2) {
    ElMessage.error('上传头像图片大小不能超过 2MB!!')
    return false
  }
  return true
}

const rules = reactive<FormRules<typeof studentInfo>>({
  stuName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  stuPhone: [{ required: true, validator: checkPhone, trigger: 'blur' }],
  studentId: [{ required: true, validator: checkStudentId, trigger: 'blur' }],
  email: [{ required: true, validator: checkEmail, trigger: 'blur' }],
  stuGrade: [{ required: true, message: '请选择年级', trigger: 'blur' }],
  stuSex: [{ required: true, message: '请选择性别', trigger: 'blur' }],
  stuSpeciality: [{ required: true, message: '请输入专业', trigger: 'blur' }],
  year: [{ required: true, message: '请选择年份', trigger: 'blur' }],
  stuDepartment: [{ required: true, message: '请选择学院', trigger: 'blur' }],
  stuSkill: [{ required: true, message: '请选择技术方向', trigger: 'blur' }],
  stuSkillStack: [{ required: true, message: '请填写个人技术栈', trigger: 'blur' }],
  stuIntention: [{ required: true, message: '请填写个人意向', trigger: 'blur' }]
})

const cancer = () => {
  disabled.value = disabled.value === false
  if (cancerButton.value === '取消') {
    getStudentInfo()
  }
  cancerButton.value = disabled.value === false ? '取消' : '修改'
}

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      console.log('保存报名信息!')
      if (typeof studentInfo.value.year != 'string')
        studentInfo.value.year = studentInfo.value.year.getFullYear()
      studentInfo.value.stuClass =
        studentInfo.value.year +
        '级' +
        studentInfo.value.stuSpeciality +
        studentInfo.value.classNumber +
        '班'
      saveInfo(studentInfo.value).then((res) => {
        if (res.data.code === 1) {
          disabled.value = true
          ElMessage({ type: 'success', message: '信息保存成功' })
          if (userstore.userInfo.studentId != studentInfo.value.studentId) {
            ElMessageBox.alert('学号已更改，请重新登陆', '提示', {
              confirmButtonText: '确定',
              callback: () => {
                Router.replace('/login')
              }
            })
          } else {
            userstore.userInfo = studentInfo.value
            studentInfo.value = {}
            getStudentInfo()
            cancerButton.value = disabled.value === false ? '取消' : '修改'
            console.log('保存成功')
            ElMessageBox.alert('报名信息已保存，请前往预约考试页进行考试预约', '提示', {
              confirmButtonText: '确定',
              callback: () => {}
            })
          }
        } else {
          ElMessage({ type: 'error', message: res.data.msg })
          console.log('保存失败')
        }
      })
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const removeContest = (item: ContestItem) => {
  const index = studentInfo.value.contest.indexOf(item)
  if (index !== -1) {
    studentInfo.value.contest.splice(index, 1)
  }
}

const addContest = () => {
  studentInfo.value.contest.push({
    key: Date.now(),
    conId: '',
    conName: '',
    conTime: ''
  })
}
</script>

<style>
.divSize {
  margin: 15px;
}

.avatar-uploader .avatar {
  z-index: 99;
  width: 100px;
  //height: 295px;
  display: block;
}

.avatar-uploader .el-upload {
  z-index: 99;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  z-index: 99;
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  z-index: 99;
  font-size: 20px;
  color: #8c939d;
  width: 100px;
  height: 150px;
  text-align: center;
}

.el-icon {
  margin-left: 8px;
  margin-right: 8px;
}

.demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-left: 8px;
  margin-right: 6px;
}
</style>
